<template>
  <div>
    <div class="check-all">
      <span>选择供货城市：</span>
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="isCheckAll"
        @change="handleCheckAllChange"
        >全选</el-checkbox
      >
    </div>
    <el-checkbox-group
      v-model="cityCodes"
      @change="handleChangeSupplyCity"
    >
      <el-checkbox
        v-for="city in supplyCitiesOptions"
        :label="city.cityCode"
        :key="city.cityCode"
        >{{ city.cityName }}
      </el-checkbox>
    </el-checkbox-group>
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
  data () {
    return {
      isIndeterminate: false,
      isCheckAll: true, // 是否全选
      cityCodes: []
    }
  },
  computed: {
    ...mapState('commonComps/referCitiesUpdate', [
      'batchSetDataVo', // 批量设置数据实例对象
      'checkedSupplyCityCodes', // 选中的供货城市code集合
      'supplyCitiesOptions', // 供货城市集合
    ]),
  },
  watch: {
    checkedSupplyCityCodes (val) {
      this.cityCodes = val
    }
  },
  methods: {
    ...mapMutations('commonComps/referCitiesUpdate', [
      'UPDATE_BATCH_SET_DATA_VO', // 更新供货城市
      'UPDATE_SUPPLY_CITIES_OPTIONS', // 更新供货城市集合
      'UPDATE_CHECKED_SUPPLY_CITY_CODES', // 更新已勾选的供货城市编码集合
    ]),
    // 全选供货城市列表
    handleCheckAllChange (val) {
      const supplyCityCodeList = this.supplyCitiesOptions.map(item => item.cityCode)
      this.cityCodes = val ? supplyCityCodeList : []
      this.UPDATE_CHECKED_SUPPLY_CITY_CODES(this.cityCodes)
      this.isIndeterminate = false
      if (!val) {
        this.UPDATE_BATCH_SET_DATA_VO({
          templateCityUuid: '',
          templateCityName: '',
        })
      }
      this.updateSupplyInfo()
    },
    // 供货城市选择是否供货
    handleChangeSupplyCity (codeList) {
      const checkedCount = codeList.length
      this.UPDATE_CHECKED_SUPPLY_CITY_CODES(codeList)
      this.isCheckAll = checkedCount === this.supplyCitiesOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.supplyCitiesOptions.length
      if (!codeList.includes(this.batchSetDataVo.templateCityUuid)) {
        this.UPDATE_BATCH_SET_DATA_VO({
          templateCityUuid: '',
          templateCityName: '',
        })
      }
      this.updateSupplyInfo()
    },
    // 更新数据
    updateSupplyInfo () {
      this.UPDATE_CHECKED_SUPPLY_CITY_CODES(this.cityCodes)
      this.$emit('update')
    }
  }
}
</script>
<style lang="less" scoped>
.check-all {
  margin-bottom: 10px;
}
</style>
